import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录 - 腾讯视频' }
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { title: '腾讯视频 - 首页', requiresAuth: true }
    },
    {
      path: '/category',
      name: 'category',
      component: () => import('../views/VideoCenterView.vue'),
      meta: { title: '视频中心', requiresAuth: true }
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('../views/SearchView.vue'),
      meta: { title: '搜索', requiresAuth: true }
    },
    {
      path: '/detail/:id',
      name: 'detail',
      component: () => import('../views/DetailView.vue'),
      meta: { title: '视频详情', requiresAuth: true }
    },
    {
      path: '/player/:id/:episodeId?',
      name: 'player',
      component: () => import('../views/PlayerView.vue'),
      meta: { title: '播放', requiresAuth: true }
    },
  // 个人中心相关路由
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/UserView.vue'),
    meta: { title: '个人中心 - 腾讯视频', requiresAuth: true }
  },
  {
    path: '/user/videos',
    name: 'my-videos',
    component: () => import('../views/MyVideosView.vue'),
    meta: { title: '我的视频 - 腾讯视频', requiresAuth: true }
  },
  {
    path: '/user/collections',
    name: 'my-collections',
    component: () => import('../views/MyCollectionsView.vue'),
    meta: { title: '我的收藏 - 腾讯视频', requiresAuth: true }
  },
  {
    path: '/user/history',
    name: 'watch-history',
    component: () => import('../views/WatchHistoryView.vue'),
    meta: { title: '观看历史 - 腾讯视频', requiresAuth: true }
  },
  {
    path: '/user/settings',
    name: 'account-settings',
    component: () => import('../views/AccountSettingsView.vue'),
    meta: { title: '账户设置 - 腾讯视频', requiresAuth: true }
  },
  {
    path: '/login-test',
    name: 'login-test',
    component: () => import('../views/LoginTestView.vue'),
    meta: { title: '登录跳转测试 - 腾讯视频' }
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import('../views/AdminView.vue'),
    meta: { title: '管理后台 - 腾讯视频', requiresAuth: true, requiresAdmin: true }
  },
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  try {
    document.title = to.meta.title || '腾讯视频'
    
    // 检查是否需要认证
    const isAuthenticated = localStorage.getItem('token') || localStorage.getItem('adminToken')
    const isAdmin = localStorage.getItem('userType') === 'admin'
    
    // 开发环境：只有在首次访问且没有token时才设置测试token
    // 避免在用户主动退出登录后重新设置token
    if (!isAuthenticated && import.meta.env.DEV && to.name !== 'login' && !from.name) {
      localStorage.setItem('token', 'test-token-for-development')
      localStorage.setItem('user', JSON.stringify({ id: 1, name: '测试用户', email: 'test@example.com' }))
      console.log('🔧 开发环境：已设置测试token')
      // 重新检查认证状态
      const finalIsAuthenticated = localStorage.getItem('token') || localStorage.getItem('adminToken')
      
      if (to.meta.requiresAuth && !finalIsAuthenticated) {
        console.log('🔒 需要认证，跳转到登录页')
        next({ name: 'login' })
      } else {
        console.log('✅ 路由正常，继续导航到:', to.name)
        next()
      }
      return
    }
    
    if (to.meta.requiresAuth && !isAuthenticated) {
      // 需要认证但没有登录，跳转到登录页
      console.log('🔒 需要认证，跳转到登录页')
      next({ name: 'login' })
    } else if (to.meta.requiresAdmin && !isAdmin) {
      // 需要管理员权限但不是管理员，跳转到首页
      console.log('👤 需要管理员权限，跳转到首页')
      next({ name: 'home' })
    } else if (to.name === 'login' && isAuthenticated && !isAdmin) {
      // 已登录访问登录页，跳转到首页
      console.log('✅ 已登录，跳转到首页')
      next({ name: 'home' })
    } else if (to.name === 'login' && isAdmin) {
      // 管理员已登录访问登录页，跳转到前端管理后台
      console.log('👨‍💼 管理员已登录，跳转到前端管理后台')
      next({ name: 'admin' })
      return
    } else if (to.path === '/' && !isAuthenticated) {
      // 未登录访问根路径，跳转到登录页
      console.log('🏠 未登录访问根路径，跳转到登录页')
      next({ name: 'login' })
    } else {
      console.log('✅ 路由正常，继续导航到:', to.name)
      next()
    }
  } catch (error) {
    console.error('❌ 路由错误:', error)
    next({ name: 'login' })
  }
})

export default router
